package com.baor.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baor.dao.PaymentFailedDao;
import com.baor.dao.WorkorderDao;
import com.baor.domain.PaymentFailedVO;
import com.baor.domain.WorkorderVO;
import com.baor.service.PaymentFailedService;
import com.baor.util.R;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PaymentFailedServiceImpl implements PaymentFailedService {

    @Autowired
    private PaymentFailedDao paymentFailedDao;

    @Autowired
    private WorkorderDao workorderDao;

    /**
     * 获取打款失败列表（分页）
     */
    @Override
    public R paymentFailedList(Map<String, Object> params) {
        try {
            // 获取分页参数
            int pageIndex = params.get("pageIndex") != null ? Integer.parseInt(params.get("pageIndex").toString()) : 1;
            int pageSize = params.get("pageSize") != null ? Integer.parseInt(params.get("pageSize").toString()) : 10;
            Page<PaymentFailedVO> page = new Page<>(pageIndex, pageSize);
            

            // 构建查询条件
            QueryWrapper<PaymentFailedVO> wrapper = new QueryWrapper<>();
            // 可根据需要添加时间范围等查询条件
            if (params.get("startTime") != null && !params.get("startTime").toString().isEmpty()) {
                wrapper.ge("application_time", params.get("startTime"));
            }
            if (params.get("endTime") != null && !params.get("endTime").toString().isEmpty()) {
                wrapper.le("application_time", params.get("endTime"));
            }

            // 执行分页查询
            IPage<PaymentFailedVO> resultPage = paymentFailedDao.selectPage(page, wrapper);

            // 封装结果
            Map<String, Object> result = new HashMap<>();
            result.put("list", resultPage.getRecords());
            result.put("totalSize", resultPage.getTotal());
//            result.put("pages", resultPage.getPages());
            result.put("pageIndex", pageIndex);
            result.put("pageSize", pageSize);
            return R.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return R.er("查询失败: " + e.getMessage());
        }
    }

    /**
     * 同步withdrawal_record中status=4的数据到wechat_payment_failure表
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R syncFailedPayments() {
        try {
            // 1. 查询withdrawal_record中status=4且未同步的数据
            MPJLambdaWrapper<WorkorderVO> wrapper = new MPJLambdaWrapper<>();
            wrapper.selectAll(WorkorderVO.class)
                    .eq(WorkorderVO::getStatus, 4)
                    // 关键修改：将withdrawal_record改为别名t
                    .notExists("SELECT 1 FROM wechat_payment_failure f " +
                            "WHERE f.user_id = t.user_id " +  // 这里使用别名t
                            "AND f.application_time = t.apply_time");  // 这里使用别名t

            List<WorkorderVO> failedRecords = workorderDao.selectJoinList(WorkorderVO.class, wrapper);

            // 后续逻辑保持不变...
            if (failedRecords.isEmpty()) {
                return R.ok("没有需要同步的失败记录");
            }

            // 同步数据到wechat_payment_failure表
            int syncCount = 0;
            for (WorkorderVO record : failedRecords) {
                PaymentFailedVO failedVO = new PaymentFailedVO();
                // 注意：确保字段映射正确，以下为示例，需根据实际实体类调整
                failedVO.setUserId(Integer.parseInt(record.getUserId()));
                failedVO.setAmount(new BigDecimal(record.getAmount()));
                failedVO.setApplicationTime(record.getApplyTime()); // 假设applyTime是Date类型
                failedVO.setNote(record.getNote()); // 失败原因
                failedVO.setCreateAt(new Date());
                failedVO.setUpdateAt(new Date());

                paymentFailedDao.insert(failedVO);
                syncCount++;
            }

            return R.ok("同步成功，共同步" + syncCount + "条记录");
        } catch (Exception e) {
            e.printStackTrace();
            return R.er("同步失败: " + e.getMessage());
        }
    }
}